package ar.edu.unlam.tpfinal.struts.actions.address;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import ar.edu.unlam.tpfinal.service.AddressService;
import ar.edu.unlam.tpfinal.service.exceptions.ServiceException;
import ar.edu.unlam.tpfinal.struts.exceptions.PresentationException;
import ar.edu.unlam.tpfinal.struts.forms.AddressForm;

public class ViewAddressAction extends BaseAddressAction {
	
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
							  	 HttpServletRequest request, HttpServletResponse response) 
			throws Exception {
		
		logger.debug("Inside ViewAddressAction");
		
		logger.debug("Getting ALL addresses");
		
		// Obtener servicio del contexto mediante Spring
		logger.debug("Getting service from context");
		WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServlet().getServletContext());
		AddressService addressService = (AddressService) context.getBean("addressService");
		
		try {
			// Mediante el servicio obtenemos TODAS las direcciones
			List<AddressForm> addressList = addressService.getAllAddresses();
		
			// Las colocamos en el request
			request.setAttribute("addressList", addressList);
			
			// Volvemos
			return mapping.findForward("success");
		} catch(ServiceException ex) {
			throw new PresentationException(ex);
		}

	}
	
}